#%%
# 过拟合练习
import cv2
import os 
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

X = np.arange(0,1,0.1)
y = np.sin(X*2*np.pi)
epsi = np.random.normal(0,0.03,size=(10,))
y = y+epsi
linex = np.arange(0,1,0.01)
plt.plot(linex,np.sin(linex*2*np.pi),c='g',label='sin')
plt.scatter(X,y)
plt.ylim(-1.5,1.5)

# 生成数据
X9 = np.ones((len(X),9))
linex9 = np.ones((len(linex),9))
for i in range(9):
    X9[:,i] = X ** (i+1)
    linex9[:,i] = linex ** (i+1)


lr = LinearRegression()
lr.fit(X9[:,0:3],y)
plt.plot(linex,lr.predict(linex9[:,0:3]),c='r',label='M=3')
print('M3 score:',lr.score(X9[:,0:3],y))
lr.fit(X9,y)
plt.plot(linex,lr.predict(linex9),c='y',label='M=9')
print('M9 score:',lr.score(X9,y))

plt.legend()
plt.show()
#%%
